package com.mali.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mali.common.dto.Result;
import com.mali.gateway.config.AuthProperties;
import com.mali.gateway.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    private final AntPathMatcher antPathMatcher;
    private final AuthProperties authProperties;
    private final JwtUtil jwtUtil;
    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        log.debug("[网关鉴权] 接收到请求 path = {}", path);

        // 2. 判断是否为无需认证路径
        if (isExcludePath(path)) {
            log.debug("[网关鉴权] 当前路径无需认证，直接放行: {}", path);
            return chain.filter(exchange);
        }

        // 3. 获取 Authorization 头中的 token
        String token = null;
        List<String> authorization = request.getHeaders().get("Authorization");
        if (!CollUtil.isEmpty(authorization)) {
            token = authorization.get(0);
        }
        log.debug("[网关鉴权] 提取到 Authorization token = {}", token);

        // 4. 校验并解析 token
        Long userId;
        try {
            userId = jwtUtil.parseToken(token);
            log.info("[网关鉴权] Token 验证成功，userId = {}", userId);
        } catch (Exception e) {
            log.warn("[网关鉴权] Token 验证失败: {}", e.getMessage());
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return writeUnauthorizedResponse(response, e.getMessage());
        }

        // 5. 将用户信息传递下游
        String userIdStr = userId.toString();
        log.debug("[网关鉴权] 将 userId 放入请求头：{}", userIdStr);
        exchange = exchange.mutate().request(builder -> builder.header("userId", userIdStr)).build();

        // 6. 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isExcludePath(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                log.debug("[网关鉴权] 匹配到排除路径: {}", excludePath);
                return true;
            }
        }
        return false;
    }

    public Mono<Void> writeUnauthorizedResponse(ServerHttpResponse response, String message) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        Result<Object> result = Result.fail(HttpStatus.UNAUTHORIZED.value(), message);
        byte[] bytes;
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            bytes = ("{\"code\":401,\"message\":\"" + message + "\"}").getBytes(StandardCharsets.UTF_8);
        }

        return response.writeWith(Mono.just(response.bufferFactory().wrap(bytes)));
    }

}
